import java.util.List;

public class MinimumTotal {

    public int minimumTotal(List<List<Integer>> triangle) {
        int m = triangle.size();
        int n = triangle.get(m - 1).size();
        int[][] dp = new int[m][n];
        dp[0][0] = triangle.get(0).get(0);
        for (int i = 1; i < m; i++) {
            dp[i][0] = triangle.get(i).get(0) + dp[i - 1][0];
        }
        int ans = dp[m - 1][0];
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < i; j++) {
                dp[i][j] = triangle.get(i).get(j) + Math.min(dp[i - 1][j], dp[i - 1][j - 1]);
                if (i == m - 1) ans = Math.min(ans, dp[i][j]);
            }
            dp[i][i] = triangle.get(i).get(i) + dp[i - 1][i - 1];
        }
        ans = Math.min(ans, dp[m - 1][m - 1]);
        return ans;
    }
}
